<template>
  <div class="box" v-if="ShowOrHide">
    <el-upload :class="urlList.length == canUploadNum ? 'opIcon' : 'sanpao'" :limit="canUploadNum" class="upload-demo"
      ref="upload" action="#" :file-list="SeeFileList" auto-upload accept=".png,.jpg" :multiple="true"
      :on-remove="removeImg" :http-request="submitUpload" list-type="picture-card" :before-upload="beforeUpload"
      :on-exceed="onExceed">
      <div slot="default" class="default">
        <i class="el-icon-plus"></i>
        <span style="color: #aaa;">最多上传{{ canUploadNum }}张图片</span>
        <span style="color: #aaa;">图片大小不超过1MB</span>
      </div>
    </el-upload>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  data() {
    return {
      fileList: [],
      // 抛出的最终图片数组
      urlList: [],
      //当前删除的序号
      index: '',
      SeeFileList: [],
      ShowOrHide: true,
    }
  },
  props: {
    canUploadNum: { //可以上传的个数
      type: Number,
      default: () => {
        return 3
      }
    },
    id: {
      type: Number,
      default: () => {
        return 0
      }
    },

    EchoImgList: { //回显的图片
      type: Array,
      default: () => {
        return []
      }
    },
    uploadUrl: {
      type: String,
      default: () => {
        return ''
      }
    },
    uploadKey1: { //上传的参数key1
      type: String,
      default: () => {
        return 'pics'
      }
    },
    uploadKey2: { //上传的参数key1
      type: String,
      default: () => {
        return 'id'
      }
    },
  },
  mounted() {
    this.urlList = []
    this.fileList = []
    if (this.EchoImgList.length > 0) {
      this.EchoImgList.forEach(el => {
        // 负责展示
        this.SeeFileList.push({
          name: el,
          url: el,
        })
        // 负责修改数据
        this.urlList.push(el)
        this.fileList.push(el)
      })
    }
  },
  methods: {
    onExceed(files, fileList) {
      this.$message.error(`最多上传${this.canUploadNum}张图片`)
    },
    beforeUpload(file) {
      // if (this.urlList.length > this.canUploadNum - 1) {
      //   this.$message.error(`最多上传${this.canUploadNum}张图片`);
      //   return false
      // }
      // 判断图片大小
      const isJPG = (file.type === 'image/jpeg') || (file.type === 'image/png');
      const isLt2M = file.size / 1024 / 1024 < 1;
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 1MB!');
      }
      return isJPG && isLt2M;
    },
    //上传文件
    async submitUpload(e) {

      console.log(e, this.uploadUrl, defaultUrl, '上传的值');
      let formData = new FormData()
      formData.append(`${this.uploadKey1}`, e.file)// 传文件
      formData.append(`${this.uploadKey2}`, this.id)// 传文件
      let res = await this.$api.ImgFile.upload(defaultUrl + this.uploadUrl, formData)
      if (res.data.code == 200) {
        this.fileList.push(e)
        this.urlList.push(res.data.data[0])
        this.$emit('getImgList', this.urlList)
      } else {
        this.$message.error('图片上传失败');
        this.clear()
      }
    },
    //删除文件
    async removeImg(e) {
      console.log(this.urlList, this.fileList, e, '删除的文件');
      this.fileList.forEach((el, i) => {
        if (e.name.indexOf('http') > -1) {//如果删除的是，回显的文件
          if (e.name == el) {
            this.index = i
          }
        } else {//如果删除的是，刚新增的文件
          if (el.file == undefined) {
            return
          }
          if (el.file.uid == e.raw.uid) {
            this.index = i
          }
        }
      })
      console.log(`删除了第${this.index}个`);
      if (this.urlList[this.index] == undefined) {
        return
      }

      setTimeout(() => {
        this.$emit('deleteImgList', this.urlList[this.index])
        console.log(this.urlList[this.index],'删除的图片');
        this.fileList.splice(this.index, 1)
        this.urlList.splice(this.index, 1)
        this.$emit('getImgList', this.urlList)
        console.log(this.urlList,'最终的图片数组');
      }, 1000)



    },
    clear() { //清除数据
      this.$refs.upload.clearFiles()
      this.urlList = []
      this.fileList = []
    },
    show() { //展示
      this.ShowOrHide = true
    },
    hide() { //隐藏
      this.ShowOrHide = false
    },
  }
}
</script>

<style lang="less" scoped>
.box {


  /deep/ .upload-demo {

    &.opIcon {
      .el-upload--picture-card {
        display: none;
      }
    }

    .default {
      display: flex;
      flex-direction: column;
      height: 100%;
      justify-content: space-evenly;
    }
  }

  /deep/ .el-upload--picture-card {
    line-height: 20px;
  }
}
</style>